import React, { useState, useEffect } from 'react';
import { Modal, Button, Space, message, Typography, Card, Row, Col, Tag, Alert, Spin, Progress, Divider } from 'antd';
import { 
  FilePptOutlined, 
  FilePdfOutlined, 
  ArrowLeftOutlined,
  LoadingOutlined,
  CheckCircleOutlined
} from '@ant-design/icons';
import jsPDF from 'jspdf';
import html2canvas from 'html2canvas';

const { Title, Text } = Typography;

interface PPTPreviewProps {
  visible: boolean;
  onClose: () => void;
  courseData: {
    title: string;
    content: string;
    knowledgePoints: any[];
    aiSuggestions: string[];
    pptOutline?: any;
  };
}

interface PPTSlide {
  title: string;
  content: string[];
  image_prompt: string;
  detail: string;
}

interface PPTData {
  title: string;
  slides: PPTSlide[];
}

const PPTPreview: React.FC<PPTPreviewProps> = ({
  visible,
  onClose,
  courseData,
}) => {
  const [pptData, setPptData] = useState<PPTData | null>(null);
  const [generating, setGenerating] = useState(false);
  const [downloadingPDF, setDownloadingPDF] = useState(false);
  const [generationProgress, setGenerationProgress] = useState(0);

  // 生成PPT数据
  const generatePPTData = async () => {
    if (!courseData) return;

    setGenerating(true);
    setGenerationProgress(0);

    try {
      // 模拟生成进度
      const progressInterval = setInterval(() => {
        setGenerationProgress(prev => {
          if (prev >= 90) {
            clearInterval(progressInterval);
            return 90;
          }
          return prev + 10;
        });
      }, 200);

      // 构建PPT大纲
      const outline = courseData.pptOutline || {
        title: `${courseData.title}教学课件`,
        slides: [
          {
            title: "课程概述",
            content: [
              "📚 课程名称：" + courseData.title,
              "👨‍🏫 授课目标：掌握核心概念",
              "📅 课程安排：系统学习",
              "🎯 学习重点：理论与实践结合"
            ],
            image_prompt: "",
            detail: "本页介绍课程的基本信息、学习目标和课程安排，为后续学习奠定基础。"
          },
          {
            title: "核心知识点",
            content: [
              "🔍 重点概念：基础理论知识",
              "⚡ 关键原理：支撑理论的重要原理",
              "🛠️ 重要方法：实用的操作技巧",
              "📊 知识结构：各知识点关联"
            ],
            image_prompt: "",
            detail: "详细讲解课程的核心知识点，帮助学生建立扎实的理论基础。"
          },
          {
            title: "实践应用",
            content: [
              "💻 操作步骤：具体实践流程",
              "⚠️ 注意事项：关键要点提醒",
              "📋 案例分析：典型应用场景",
              "🎯 应用技巧：提高效率方法"
            ],
            image_prompt: "",
            detail: "展示实际应用和操作过程，让学生能够将理论知识转化为实践技能。"
          },
          {
            title: "学习总结",
            content: [
              "📝 知识回顾：核心要点总结",
              "🔗 知识联系：与其他课程关联",
              "🚀 拓展方向：进一步学习建议",
              "💡 学习建议：提高学习效果"
            ],
            image_prompt: "",
            detail: "总结课程内容，帮助学生巩固所学知识，并为后续学习提供指导。"
          }
        ]
      };

      // 模拟生成时间
      await new Promise(resolve => setTimeout(resolve, 2000));

      clearInterval(progressInterval);
      setGenerationProgress(100);

      setPptData(outline);
      message.success("PPT预览生成成功！");

    } catch (error) {
      console.error("PPT生成失败:", error);
      message.error("PPT预览生成失败，请重试");
    } finally {
      setGenerating(false);
      setGenerationProgress(0);
    }
  };

  // 生成PDF文件
  const handleDownloadPDF = async () => {
    if (!pptData || !courseData) {
      message.error("请先生成PPT预览");
      return;
    }

    setDownloadingPDF(true);
    try {
      // 创建一个临时的HTML内容用于渲染
      const createHTMLContent = () => {
        const html = `
          <!DOCTYPE html>
          <html>
          <head>
            <meta charset="UTF-8">
            <style>
              body {
                font-family: 'Microsoft YaHei', 'SimSun', Arial, sans-serif;
                margin: 0;
                padding: 20px;
                background: white;
                color: black;
                line-height: 1.6;
              }
              .title {
                font-size: 24px;
                font-weight: bold;
                text-align: center;
                margin-bottom: 30px;
                color: #333;
              }
              .section {
                margin-bottom: 20px;
              }
              .section-title {
                font-size: 16px;
                font-weight: bold;
                margin-bottom: 10px;
                color: #1890ff;
              }
              .content {
                font-size: 12px;
                margin-left: 10px;
              }
              .slide {
                margin-bottom: 15px;
                padding: 10px;
                border-left: 3px solid #1890ff;
                background: #f8f9fa;
              }
              .slide-title {
                font-size: 14px;
                font-weight: bold;
                margin-bottom: 8px;
                color: #333;
              }
              .slide-content {
                font-size: 12px;
                margin-left: 10px;
              }
              .slide-content ul {
                margin: 5px 0;
                padding-left: 20px;
              }
              .slide-content li {
                margin-bottom: 3px;
              }
              .footer {
                font-size: 10px;
                color: #666;
                text-align: center;
                margin-top: 20px;
                border-top: 1px solid #eee;
                padding-top: 10px;
              }
            </style>
          </head>
          <body>
            <div class="title">${pptData.title || '课程课件'}</div>
            
            <div class="section">
              <div class="section-title">课程信息</div>
              <div class="content">
                <strong>课程标题：</strong>${courseData.title || ''}<br>
                ${courseData.content ? `<strong>课程内容：</strong>${courseData.content}` : ''}
              </div>
            </div>
            
            ${courseData.knowledgePoints && courseData.knowledgePoints.length > 0 ? `
            <div class="section">
              <div class="section-title">知识点</div>
              <div class="content">
                ${courseData.knowledgePoints.map(kp => `• ${kp.name}: ${kp.content}`).join('<br>')}
              </div>
            </div>
            ` : ''}
            
            ${pptData.slides && pptData.slides.length > 0 ? `
            <div class="section">
              <div class="section-title">幻灯片内容</div>
              ${pptData.slides.map((slide, index) => `
                <div class="slide">
                  <div class="slide-title">第${index + 1}页：${slide.title}</div>
                  <div class="slide-content">
                    ${slide.content && slide.content.length > 0 ? `
                      <strong>内容要点：</strong><br>
                      <ul>
                        ${slide.content.map(item => `<li>${item}</li>`).join('')}
                      </ul>
                    ` : ''}
                    ${slide.detail ? `
                      <strong>详细说明：</strong><br>
                      ${slide.detail}
                    ` : ''}
                  </div>
                </div>
              `).join('')}
            </div>
            ` : ''}
            
            ${courseData.aiSuggestions && courseData.aiSuggestions.length > 0 ? `
            <div class="section">
              <div class="section-title">AI建议</div>
              <div class="content">
                ${courseData.aiSuggestions.map(suggestion => `• ${suggestion}`).join('<br>')}
              </div>
            </div>
            ` : ''}
            
            <div class="footer">
              生成时间：${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}
            </div>
          </body>
          </html>
        `;
        return html;
      };

      // 创建临时容器
      const container = document.createElement('div');
      container.style.position = 'absolute';
      container.style.left = '-9999px';
      container.style.top = '0';
      container.style.width = '800px';
      container.style.backgroundColor = 'white';
      container.style.padding = '20px';
      container.innerHTML = createHTMLContent();
      document.body.appendChild(container);

      // 使用html2canvas渲染为图片
      const canvas = await html2canvas(container, {
        scale: 2,
        useCORS: true,
        allowTaint: true,
        backgroundColor: '#ffffff',
        width: 800,
        height: container.scrollHeight
      });

      // 移除临时容器
      document.body.removeChild(container);

      // 创建PDF
      const pdf = new jsPDF('p', 'mm', 'a4');
      const imgWidth = 210; // A4宽度
      const pageHeight = 295; // A4高度
      const imgHeight = (canvas.height * imgWidth) / canvas.width;
      let heightLeft = imgHeight;
      let position = 0;

      // 添加图片到PDF
      pdf.addImage(canvas.toDataURL('image/jpeg', 0.8), 'JPEG', 0, position, imgWidth, imgHeight);
      heightLeft -= pageHeight;

      // 如果内容超过一页，添加新页面
      while (heightLeft >= 0) {
        position = heightLeft - imgHeight;
        pdf.addPage();
        pdf.addImage(canvas.toDataURL('image/jpeg', 0.8), 'JPEG', 0, position, imgWidth, imgHeight);
        heightLeft -= pageHeight;
      }

      // 保存PDF文件
      const filename = `${courseData.title || '课程'}_课件_${new Date().toISOString().slice(0, 10)}.pdf`;
      pdf.save(filename);
      
      message.success("PDF文件下载成功！");
    } catch (error) {
      console.error("PDF生成失败:", error);
      message.error("PDF文件生成失败，请重试");
    } finally {
      setDownloadingPDF(false);
    }
  };

  // 当模态框打开时自动生成PPT
  useEffect(() => {
    if (visible && !pptData) {
      generatePPTData();
    }
  }, [visible]);

  return (
    <Modal
      title={
        <Space>
          <FilePptOutlined style={{ color: '#1890ff' }} />
          <span>PPT预览</span>
        </Space>
      }
      open={visible}
      onCancel={onClose}
      width="75%"
      style={{ top: 20 }}
      footer={[
        <Button key="back" onClick={onClose} icon={<ArrowLeftOutlined />}>
          返回
        </Button>,
        <Button
          key="download-pdf"
          type="primary"
          icon={<FilePdfOutlined />}
          loading={downloadingPDF}
          onClick={handleDownloadPDF}
          disabled={!pptData}
        >
          {downloadingPDF ? "正在生成PDF..." : "下载PDF文件"}
        </Button>,
      ]}
    >
      <div style={{ padding: '24px', background: '#f5f5f5', minHeight: '60vh' }}>
        {generating ? (
          <div style={{ textAlign: 'center', padding: '40px' }}>
            <Spin
              indicator={<LoadingOutlined style={{ fontSize: 48 }} spin />}
            />
            <div style={{ marginTop: 16 }}>
              <Text>正在生成PPT预览...</Text>
            </div>
            <Progress
              percent={generationProgress}
              status="active"
              style={{ marginTop: 16, maxWidth: 300 }}
            />
          </div>
        ) : pptData ? (
          <>
            <Alert
              message="PPT预览生成成功"
              description="您可以预览PPT内容，满意后点击下载按钮获取PDF文件。PDF文件包含完整的课程内容，适合打印和分享。"
              type="success"
              showIcon
              style={{ marginBottom: 24 }}
            />
            
            <Card style={{ marginBottom: 24 }}>
              <Title level={2} style={{ textAlign: 'center', color: '#1890ff' }}>
                {pptData.title}
              </Title>
              <Divider />
              <Row gutter={16}>
                <Col span={8}>
                  <Text strong>总页数：</Text>
                  <Tag color="blue">{pptData.slides.length} 页</Tag>
                </Col>
                <Col span={8}>
                  <Text strong>课程：</Text>
                  <Text>{courseData.title}</Text>
                </Col>
                <Col span={8}>
                  <Text strong>状态：</Text>
                  <Tag color="green" icon={<CheckCircleOutlined />}>
                    已生成
                  </Tag>
                </Col>
              </Row>
            </Card>

            <Row gutter={[16, 16]}>
              {pptData.slides.map((slide, index) => (
                <Col span={24} key={index}>
                  <Card 
                    title={
                      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                        <span style={{ fontSize: '16px', fontWeight: 'bold' }}>
                          📄 第 {index + 1} 页：{slide.title}
                        </span>
                        <Tag 
                          color="blue" 
                          style={{ 
                            fontSize: '14px', 
                            fontWeight: 'bold',
                            borderRadius: '12px',
                            padding: '4px 12px'
                          }}
                        >
                          {index + 1}
                        </Tag>
                      </div>
                    }
                    style={{ 
                      marginBottom: 20, 
                      borderRadius: 12,
                      boxShadow: '0 4px 16px rgba(0, 0, 0, 0.1)',
                      minHeight: '450px',
                      border: '1px solid #e8e8e8'
                    }}
                    headStyle={{
                      background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                      color: 'white',
                      borderRadius: '12px 12px 0 0',
                      padding: '16px 24px'
                    }}
                  >
                    <div style={{ marginBottom: 16 }}>
                      <Text strong style={{ fontSize: '16px', color: '#1890ff' }}>内容要点：</Text>
                      <div style={{ marginTop: 8 }}>
                        {slide.content.map((item, idx) => {
                          // 检测内容类型并应用不同样式
                          const isEmoji = /^[📚👨‍🏫📅🎯🔍⚡🛠️📊💻⚠️📋🎯]/.test(item);
                          const isList = item.includes('：') || item.includes(':');
                          
                          return (
                            <div 
                              key={idx}
                              style={{
                                padding: '12px 16px',
                                margin: '8px 0',
                                background: isEmoji ? 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)' : '#f8f9fa',
                                borderRadius: 8,
                                borderLeft: isEmoji ? '4px solid #1890ff' : '3px solid #52c41a',
                                boxShadow: isEmoji ? '0 2px 8px rgba(102, 126, 234, 0.2)' : '0 1px 4px rgba(0, 0, 0, 0.1)',
                                transition: 'all 0.3s ease'
                              }}
                            >
                              <Text 
                                style={{ 
                                  color: isEmoji ? 'white' : '#333',
                                  fontWeight: isEmoji ? 'bold' : 'normal',
                                  fontSize: isEmoji ? '14px' : '13px'
                                }}
                              >
                                {item}
                              </Text>
                            </div>
                          );
                        })}
                      </div>
                    </div>

                    <div style={{ marginTop: 16 }}>
                      <Text strong style={{ fontSize: '16px', color: '#722ed1' }}>详细说明：</Text>
                      <div 
                        style={{
                          marginTop: 8,
                          padding: '12px 16px',
                          background: 'linear-gradient(135deg, #f9f0ff 0%, #f0f5ff 100%)',
                          borderRadius: 8,
                          border: '1px solid #d3adf7',
                          boxShadow: '0 2px 8px rgba(114, 46, 209, 0.1)'
                        }}
                      >
                        <Text style={{ 
                          margin: 0, 
                          fontSize: '13px', 
                          color: '#531dab',
                          lineHeight: '1.6'
                        }}>
                          {slide.detail}
                        </Text>
                      </div>
                    </div>
                  </Card>
                </Col>
              ))}
            </Row>
          </>
        ) : (
          <div style={{ textAlign: 'center', padding: '40px' }}>
            <Text type="secondary">暂无PPT数据</Text>
          </div>
        )}
      </div>
    </Modal>
  );
};

export default PPTPreview; 